package com.tcp;

import com.alibaba.fastjson.JSONObject;
import com.binary.BinaryMessageType;
import io.netty.buffer.Unpooled;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.device.DeviceOperator;
import org.jetlinks.core.device.session.DeviceSessionManager;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.interceptor.DeviceMessageSenderInterceptor;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;




@Slf4j
@AllArgsConstructor
public class TcpMessageSenderInterceptor implements DeviceMessageSenderInterceptor {

    private DeviceSessionManager sessionManager;

    @Override
    public <R extends DeviceMessage> Flux<R> afterSent(DeviceOperator device, DeviceMessage message, Flux<R> reply) {
        if (message instanceof FunctionInvokeMessage) {
            //将平台下发的消息编码为设备可识别的二进制报文
            byte[] encodeMessage = BinaryMessageType.write(message, Unpooled.buffer()).array();
            log.info("encodeMessage:{}",encodeMessage);
            return sessionManager
                    .getSession(device.getDeviceId())
                    .flatMap(session -> session.
                            //拿到session，调用send方法向设备发送编码之后的报文
                                    send(EncodedMessage.simple(Unpooled.wrappedBuffer(JSONObject.toJSONBytes(encodeMessage))))
                    )
                    .thenMany(Mono.empty());
        }
        return Flux.empty();
    }
}
